package com.bluegalaxy.sitescore.controller;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Permission;
import com.bluegalaxy.sitescore.common.Uploader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2018/1/9 0009.
 */
@Controller
@RequestMapping("/Ueditor")
public class UeditorController {

    @ResponseBody
    @Permission(action = Action.Skip)
    @RequestMapping(value = "/uploadImage",method = RequestMethod.POST)
    public String uploadImage(@RequestParam(value = "upfile", required = false) MultipartFile multipartFile,HttpServletRequest request){
        try {
            request.setCharacterEncoding("utf-8");
            Uploader up = new Uploader(request);
            String pathStr="upload";
            up.setSavePath(pathStr);
            String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
            up.setAllowFiles(fileType);
            up.setMaxSize(10000); //单位KB
            up.setMultipartFile(multipartFile);
            up.upload();
            String callback = request.getParameter("callback");
            String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize() + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
            result = result.replaceAll("\\\\", "\\\\");
            if (callback == null) {
                //response.getWriter().print( result );
                return result;
            } else {
                //response.getWriter().print("<script>"+ callback +"(" + result + ")</script>");
                return "<script>" + callback + "(" + result + ")</script>";
            }
        }
        catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }
}
